import 'package:get/get.dart';
import 'package:psi/base/base_controller.dart';
import 'package:psi/routes/app_pages.dart';

import '../../entity/response/login_resp.dart';
import '../../http/api_service.dart';
import '../../utils/utils.dart';
import 'login_state.dart';

class LoginLogic extends BaseController {
  final LoginState state = LoginState();

  @override
  void onReady() {
    // TODO: implement onReady
    super.onReady();
  }

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
  }

  void goToRegister() {
    Get.toNamed(PageNames.register);
  }

  void loginAction() async {
    if (state.req.value.account?.isEmpty ?? true) {
      showToast("请输入用户名/手机号");
      return;
    }
    if (state.req.value.password?.isEmpty ?? true) {
      showToast("请输入密码");
      return;
    }

    try {
      showLoading();
      LoginResp resp = await ApiService.request.loginByPwd(state.req.value);
      if (resp.code == 0) {
        Utils.userLogic.loginSuccess(resp);
      } else {
        showToast(resp.message);
      }
      hideLoading();
    } catch(e) {
      Utils.logE(e);
      hideLoading();
    }
  }
}
